﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WinSCP;
using System.Net;
using System.IO;

namespace Sync3DCartDatabase
{
    public static class CFTPHelper
    {
        #region Public Methods

        public static void Download(CSessionOptionCDO objSessionOption, MemoryStream fileInMemory, string fileName)
        {
            FtpWebRequest reqFTP;
            Stream ftpStream = null;
            FtpWebResponse response = null;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + objSessionOption.HostName + "/" + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                if (objSessionOption.FtpSecure == FTPSecure.ExplicitSsl)
                    reqFTP.EnableSsl = true;
                reqFTP.Credentials = new NetworkCredential(objSessionOption.UserName, objSessionOption.Password);
                response = (FtpWebResponse)reqFTP.GetResponse();
                ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    fileInMemory.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
            }
            finally
            {
                if(ftpStream != null)
                    ftpStream.Close();
                if(response != null)
                    response.Close();
            }
        }

        public static void DownloadFile(CSessionOptionCDO objSessionOption, string strSourceFile, string strDestinationPath, bool isFileToBeRemoved = false)
        {
            if (null == objSessionOption)
                throw new ArgumentNullException("objSessionOption");

            SessionOptions sessionOptions = PopulateSessionOptions(objSessionOption);

            using (Session session = new Session())
            {
                // Connect
                session.Open(sessionOptions);

                // Transfer mode 
                TransferOptions transferOptions = new TransferOptions();
                transferOptions.TransferMode = TransferMode.Binary;

                TransferOperationResult transferResult;
                transferResult = session.GetFiles(strSourceFile, strDestinationPath, isFileToBeRemoved, transferOptions);

                // Throw on any error
                transferResult.Check();

                // Print results
                //foreach (TransferEventArgs transfer in transferResult.Transfers)
                //{
                //    Console.WriteLine("download of {0} succeeded", transfer.FileName);
                //}
            }
        }

        #endregion

        #region Private Methods

        private static SessionOptions PopulateSessionOptions(CSessionOptionCDO objSessionOption)
        {
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = objSessionOption.Protocol == FTPProtocol.FTP ? Protocol.Ftp : Protocol.Sftp,
                HostName = objSessionOption.HostName,
                UserName = objSessionOption.UserName,
                Password = objSessionOption.Password
            };

            if (objSessionOption.PortNumber > 0)
                sessionOptions.PortNumber = objSessionOption.PortNumber;

            sessionOptions.FtpSecure = (FtpSecure)Enum.Parse(typeof(FTPSecure), objSessionOption.FtpSecure.ToString());

            if (sessionOptions.FtpSecure == FtpSecure.ExplicitSsl)
                sessionOptions.SslHostCertificateFingerprint = objSessionOption.SslHostCertificateFingerprint;

            if (!string.IsNullOrWhiteSpace(objSessionOption.SshHostKeyFingerprint))
                sessionOptions.SshHostKeyFingerprint = objSessionOption.SshHostKeyFingerprint;

            return sessionOptions;
        }
        #endregion
    }
}
